import { useReactive } from 'ahooks';
import { Modal, message } from 'antd';
import Cookies from 'js-cookie';
import { useCallback, useEffect, useState } from 'react';
import { history } from 'umi';

import { reFreshToken } from '@/services/login';
import { forWechatPay } from '@/services/orderManage';
import { getErrorMsg } from '@/util/utils';

interface Props {
  payStatusVisible: boolean;
  setPayStatusVisible: (a: boolean) => void;
  id: string;
}

let timer: any;

export default function PayModal(props: Props) {
  const [payStatus, setPayStatus] = useState(false);
  // const [confirmLoading, setConfirmLoading] = useState(false);
  const state = useReactive({
    confirmLoading: false,
  });
  const { payStatusVisible, setPayStatusVisible, id } = props;

  const handleFreshToken = async () => {
    const refreshToken = localStorage.getItem('refreshToken');
    const res = await reFreshToken({
      refreshToken,
    });
    if (res.code == 200) {
      localStorage.setItem('refreshToken', res.data.refreshToken);
      if (Cookies.get('isAutoLogin') === 'true') {
        Cookies.set('saas_token', 'Bearer ' + res.data.token, { expires: res.data.expire / 86400 });
      } else {
        Cookies.set('saas_token', 'Bearer ' + res.data.token);
      }
    } else {
      message.error(getErrorMsg(res));
    }
  };

  const polling = useCallback(async (ids: string, secondCheck?: boolean) => {
    const res = await forWechatPay(ids);
    // secondCheck=true 二次验证
    if (!secondCheck) {

      if (state.confirmLoading) {
        clearInterval(timer);
        return;
      }
    }
    if (res.code === 200) {
      timer = setInterval(() => {
        clearInterval(timer);
        polling(ids, secondCheck);
      }, 1000);
    } else {
      message.error(getErrorMsg(res));
      clearInterval(timer);
      return;
    }

    if (res.data?.success) {
      setPayStatusVisible(false);
      clearInterval(timer);
      setPayStatus(true);
      message.success('支付成功！即将跳转到个人中心');
      setTimeout(() => {
        history.push('/PersonCenter?status=3');
      }, 1000);
      // 付款成功书刷新token
      await handleFreshToken();
      return;
    } else if (res?.message?.length > 0) {
      message.error(getErrorMsg(res));
    }
  }, [state.confirmLoading]);

  useEffect(() => {
    if (payStatusVisible) {
      polling(id, false);
    }
    return () => {
      clearInterval(timer);
    };
  }, [payStatusVisible]);

  const handleOk = () => {
    clearInterval(timer);
    // setConfirmLoading(true);
    state.confirmLoading = true;
    if (payStatusVisible) {
      polling(id, true);
    }
  };
  return (
    <div>
      <Modal confirmLoading={state.confirmLoading} closable={false} maskClosable={false}
             okText={state.confirmLoading ? '正在查询支付状态' : '支付完成'} destroyOnClose title="支付状态" visible={payStatusVisible}
             onCancel={() => {
               setPayStatusVisible(false);
               history.push('/PersonCenter?status=3');
             }} onOk={handleOk}>
        {payStatus ? '已支付，点击支付完成回到订单页' : '支付中...'}
      </Modal>
    </div>
  );
}
